package com.heaven.schedule;

import com.heaven.constant.MessageConstants;
import com.heaven.core.entity.MessageEntity;
import com.heaven.service.MessageService;
import com.heaven.utils.RedisUtils;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

@Slf4j
@Component
public class MessageSchedule {
    @Resource
    private ScheduledExecutorService scheduledExecutorService;
    @Resource
    private RedisUtils redisUtils;
    @Resource
    private MessageService messageService;

    @Scheduled(fixedRate = 30, timeUnit = TimeUnit.MINUTES)
    private void saveMsgCache() {
        CompletableFuture.runAsync(() -> {
            log.info("保存消息缓存>>>>>>>>>>>>");
            List<String> keys = redisUtils.keys(MessageConstants.MESSAGE_CACHE + "*:*").stream().toList();
            for (String key : keys) {
                MessageEntity messageEntity = redisUtils.getCacheObject(key);
                messageService.save(messageEntity);
                redisUtils.deleteObject(key);
            }
        }, scheduledExecutorService);
    }
}
